// /* eslint-disable indent */
import React, { useState, useEffect } from 'react';

import { useDispatch } from 'react-redux';

import { View, router, hideMenuButton, showLoading, hideLoading, Text } from '@ray-js/ray';
import { Dialog, NavBar } from '@ray-js/smart-ui';

import _ from 'lodash';
import { updateTimerList } from '@/redux/modules/scheduleStateSlice';
import { useDpIdByCode } from '@/hooks/useDpIdByCode';
import Slider2 from '@/components/Slider2';
import { NavBarCustom } from '@/components/NavBarCustom';

import Strings from '../i18n';
import Weeks from '../component/weeks';

import Picker from '../component/picker';
// import Calendar from '../component/calendar';

import { addSchedule, updateSchedule } from '../utils';
import { AddOrEditParams, TimerModel } from '../type';

import styles from './index.module.less';

export default function AddSchedule({ location }) {
  const [percentID] = useDpIdByCode<string[]>(['percent_control']);

  const { query } = location;

  const isEdit = query?.isEdit === 'true';

  const currentInfo = JSON.parse(query?.currentInfo || '{}') as TimerModel;

  const { timerId, time: originTime, loops, aliasName, dps: originDps } = currentInfo;

  const getTime = () => {
    const now = new Date();
    const hour = now.getHours();
    const minute = now.getMinutes();

    if (isEdit) {
      const [hour, minute] = originTime.split(':');
      return {
        hour: +hour,
        minute: +minute,
      };
    }
    return {
      hour,
      minute,
    };
  };

  const getWeeks = () => {
    if (isEdit) {
      return loops.split('').map(Number);
    }
    return [0, 0, 0, 0, 0, 0, 0];
  };

  const getNote = () => {
    if (isEdit) {
      return aliasName;
    }
    return '';
  };

  const getDps = () => {
    if (isEdit) {
      return originDps;
    }

    return {
      [percentID]: 50,
    };
  };

  const [weeks, setWeeks] = useState<number[]>(getWeeks);
  const [note, setNote] = useState<string>(getNote);
  const [time, setTime] = useState(getTime);
  const [dps, setDps] = useState<Record<string, any>>(getDps);

  const dispatch = useDispatch();

  const handlePickerChange = (value: { hour: number; minute: number }) => {
    setTime(value);
  };

  const handleWeeksChange = (value: any) => {
    setWeeks(value);
  };

  const handleNoteChange = (value: string) => {
    setNote(value);
  };

  const handleActionChange = (value: Record<string, any>) => {
    setDps(value);
  };

  useEffect(() => {
    hideMenuButton();
  }, []);

  const handleSave = async () => {
    const Api = isEdit ? updateSchedule : addSchedule;

    const { hour, minute } = time;

    const timeStr = `${_.padStart(`${hour}`, 2, '0')}:${_.padStart(`${minute}`, 2, '0')}`;

    const params: AddOrEditParams = {
      time: timeStr,
      loops: weeks.join(''),
      aliasName: note,
      dps,
    };

    if (isEdit) {
      params.timerId = timerId;
    }
    console.log('🚀 ~ file: index.tsx:131 ~ params:', params);

    showLoading();
    Api(params).then(res => {
      hideLoading();
      dispatch(updateTimerList(res));
      router.back();
    });
  };

  const onClickLeft = React.useCallback(event => {
    router.back();
  }, []);

  const renderModeaAtion = () => {
    return (
      <View className={styles.card}>
        <Text>{Strings.getLang('percent_control')}</Text>
        <View className={styles.slider}>
          <Slider2
            control=""
            leftValue={dps[percentID]}
            rightValue={dps[percentID]}
            bindchangend={e => {
              setDps({
                ...dps,
                [percentID]: e.detail.value?.percent,
              });
            }}
            mode="same"
          />
        </View>
      </View>
    );
  };

  return (
    <View className={styles.view}>
      <NavBarCustom
        name={isEdit ? Strings.getLang('editTimer') : Strings.getLang('addTimer')}
        back
      />

      <Picker time={time} handlePickerChange={handlePickerChange} />

      <Weeks style={{ marginTop: 32 }} weeks={weeks} onChange={handleWeeksChange} />
      {renderModeaAtion()}

      <View className={styles.saveBtn} onClick={handleSave}>
        <Text>{Strings.getLang('save')}</Text>
      </View>

      <Dialog id="smart-dialog" />
    </View>
  );
}
